package com.LeeCode;

import java.util.Arrays;

/**
 * 将 x 减到 0 的最小操作数
 */

public class Code1658 {
    public static void main(String[] args) {
        int[] nums = {3, 2, 20, 1, 1, 3};
        int x = 10;
        System.out.println(new Code1658().minOperations(nums, x));
    }

    public int minOperations(int[] nums, int x) {
        int n = nums.length;
        int total = Arrays.stream(nums).sum();
        int target = total - x;

        if (target == 0)
            return n;
        if (target < 0)
            return -1;

        int left = 0, ans = -1, sum = 0;
        for (int i = 0; i < n; i++) {
            sum += nums[i];
            while (sum > target && left < n) {
                sum -= nums[left++];
            }
            if (sum == target) {
                ans = Math.max(ans, i - left + 1);
            }
        }
        return ans == -1 ? -1 : n - ans;
    }
}
